When I started writing this question, I read a lot of other similar questions on the same topic but still couldn't find my own answer.
The problem appears when I approach playing audio using "new Audio()" of HTMLAudioElement (Web APIs https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement). Specifically, how to control the running sound that way?
See the following example. If it is not possible to control those running HTMLAudioElements, it will become a disaster for the user. The sounds will overlap and a mess will occur. The sounds will overlap and a mess will occur.
setTimeout
(
function ()
{
let audio = new Audio("https://www.bensound.com/bensound-music/bensound-dreams.mp3");
audio.autoplay = true;
audio.play()
.then(function ()
{
console.log("Audio 01 is playing.");
})
},
1000 // Audio has a duration of about 2 to 3 minutes
)
setTimeout
(
function ()
{
let audio = new Audio("https://www.bensound.com/bensound-music/bensound-ukulele.mp3");
audio.autoplay = true;
audio.play()
.then(function ()
{
console.log("Audio 02 is playing.");
})
},
5000 // Audio has a duration of about 2 to 3 minutes
)
setTimeout
(
function ()
{
let audio = new Audio("https://www.bensound.com/bensound-music/bensound-creativeminds.mp3");
audio.autoplay = true;
audio.play()
.then(function ()
{
console.log("Audio 03 is playing.");
})
},
10000 // Audio has a duration of about 2 to 3 minutes
)
I know it's possible to get around that problem by creating an "audio" tag with some identifier, like an id or a class. And so the problem will be solved with a few lines of simple JS.
But what if we have to deal with this problem? Any comments or feedback is highly appreciated. Thanks.
Consider maintaining a list of all Audio elements created and pause the others when one starts playing:
const GroupedAudio = (() => {
const audios = [] // all Audio elements created
return function() {
const audio = new Audio(...arguments)
audios.push(audio)
// Pause other Audio when this one starts
audio.addEventListener('play', () => {
for (let a of audios) {
if (a !== audio) {
a.pause()
}
}
})
return audio
}
})()
const audio1 = new GroupedAudio('https://www.bensound.com/bensound-music/bensound-dreams.mp3')
const audio2 = new GroupedAudio('https://www.bensound.com/bensound-music/bensound-ukulele.mp3')
const audio3 = new GroupedAudio('https://www.bensound.com/bensound-music/bensound-creativeminds.mp3')
<button onclick="audio1.play()">Play 1</button>
<button onclick="audio2.play()">Play 2</button>
<button onclick="audio3.play()">Play 3</button>